package com.leap.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.leap.entity.ChatRecord;
import com.leap.entity.Message;
import com.leap.entity.RestBean;
import com.leap.entity.vo.ChatRecordVO;
import com.leap.entity.vo.ChatRecordVOList;
import com.leap.service.ChatRecordService;
import com.leap.utils.Const;
import com.leap.utils.JwtUtils;
import com.leap.utils.KimiChatClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/kimi")
@Slf4j
@Tag(name = "Kimi-AI对话服务")
public class KimiController {

    @Value("${knowlab.kimi.apiKey}")
    private String apiKey;

    @Autowired
    private ChatRecordService chatRecordService;

    @Autowired
    private JwtUtils utils;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送与AI对话请求
     * @param question
     * @param request
     * @return
     * @throws IOException
     */
    @Operation(summary = "与Kimi对话的请求")
    @PostMapping("/chat")
    public RestBean<Message> doChat(@RequestBody JSONObject question,
                                   HttpServletRequest request) throws IOException {
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);
        String chatKey = Const.CHAT_SESSION + accountId;

        //判断当前用户特定会话缓存
        List<Message> messageList = redisTemplate.opsForList().range(chatKey, 0, -1);
        if (messageList.size() == 0){
            //初始化会话集合缓存
            Set keys = redisTemplate.keys(chatKey);
            redisTemplate.delete(keys);
            messageList = chatRecordService.initMessages();
        }

        String ask = question.getString("question");
        messageList.add(new Message("user", ask));

        //大于30轮对话左右 保存并提示对话长度已达最长 需新建对话
        if (messageList.size() >= 64){
            //删除最后一个对话元素
            messageList.remove(messageList.size()-1);
            return RestBean.failure(400, "对话长度已达最长！ 请新建对话");
        }

        log.info("messageList: {}", messageList);

        //创建对话类
        KimiChatClient kimiChatClient = new KimiChatClient(apiKey);
        Message message = kimiChatClient.sendRequest(messageList);

        messageList.add(message);

        //刷新当前用户对话缓存
        Set keys = redisTemplate.keys(chatKey);
        redisTemplate.delete(keys);

        redisTemplate.opsForList().rightPushAll(chatKey, messageList);
        redisTemplate.expire(chatKey, 24, TimeUnit.HOURS);

        log.info("messageList: {}", messageList);

        return RestBean.success(message);
    }

    /**
     * 离开AI对话界面
     * @param num
     * @param request
     * @return
     */
    @Operation(summary = "退出AI对话页面")
    @PutMapping("/quit")
    public RestBean<String> quitChat(@RequestParam(defaultValue = "0") int num,
                                     @RequestParam(defaultValue = "") String title,
                                     HttpServletRequest request){
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);
        String key = Const.CHAT_SESSION + accountId;
        List<Message> messageList = redisTemplate.opsForList().range(key, 0, -1);

        chatRecordService.saveMessages(accountId,messageList,num,title);

        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);

        return RestBean.success("保存成功");
    }

    /**
     * 获取用户AI对话记录集合
     * @param request
     * @return
     */
    @Operation(summary = "获取用户AI对话记录集合")
    @GetMapping("/list")
    public RestBean<ChatRecordVOList> getChatRecordList(HttpServletRequest request){
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);

        List<ChatRecord> list = chatRecordService.getChatSumByAccountId(accountId);
        int size = list.size();

        List<ChatRecordVO> VOList = list.stream().map(item ->
                ChatRecordVO.builder()
                .chatId(item.getId())
                .accountId(item.getAccountId())
                .num(item.getNum())
                .title(item.getTitle()==null?"咨询记录"+item.getNum(): item.getTitle())
                .updateTime(item.getUpdateTime())
                .build()
        ).toList();

        ChatRecordVOList chatRecordVOList = ChatRecordVOList.builder()
                .chatRecordList(VOList)
                .sum(size)
                .build();

        return RestBean.success(chatRecordVOList);
    }


    /**
     * 获取与AI对话详细内容
     * @param chatId
     * @param request
     * @return
     */
    @Operation(summary = "打开对话获取用户AI对话详情")
    @GetMapping("/intoMessage")
    public RestBean<List<Message>> getMessages(Long chatId,
                                               HttpServletRequest request) {
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);

        String chatKey = Const.CHAT_SESSION + accountId;

        Set keys = redisTemplate.keys(chatKey);
        redisTemplate.delete(keys);

        LambdaQueryWrapper<ChatRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatRecord::getAccountId, accountId);
        queryWrapper.eq(ChatRecord::getId,chatId);

        List<ChatRecord> chatRecords = chatRecordService.list(queryWrapper);
        ChatRecord chatRecord = chatRecords.get(0);

        List<Message> messageList = JSONArray.parseArray(chatRecord.getMessage(), Message.class);

        redisTemplate.opsForList().rightPushAll(chatKey, messageList);

        return RestBean.success(messageList);
    }

    /**
     *
     * 修改咨询记录标题
     * @param chatId
     * @param title
     * @param request
     * @return
     */
    @Operation(summary = "修改咨询记录标题")
    @PostMapping("/update")
    public RestBean<String> modifyTitle(Long chatId,
                                        String title,
                                        HttpServletRequest request) {
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);

        chatRecordService.updateTitle(accountId,chatId,title);

        return RestBean.success("保存成功");
    }
}
